<template>
  <div class="insert-page">
    <el-form :model="formData" label-width="100px">
      <el-tabs>
        <el-tab-pane label="基本信息">
          <el-row>
            <el-col :span="5">
              <el-form-item label="名称" required>
                <el-input placeholder="请输入名称" v-model="formData.name"></el-input>
                <span v-if="nameError" style="color: red;" class="error-message">{{ nameError }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="规格">
                <el-input placeholder="请输入规格" v-model="formData.standard"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="型号">
                <el-input placeholder="请输入型号" v-model="formData.model"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="9">
              <el-row :gutter="20"> <!-- 控制列之间的间距 -->
                <el-col :span="20"> <!-- 20个栅格 -->
                  <el-form-item label="单位" required>
                    <template v-if="formData.multiUnit">
                      <el-select v-model="formData.unitId" placeholder="请选择多单位" @change="handleUnitChange">
                        <el-option v-for="item in da" :key="item.id" :label="item.name" :value="item.id" />
                      </el-select>
                    </template>
                    <template v-else>
                      <el-input placeholder="请选择单位" v-model="formData.unit" @input="updateUnits"></el-input>
                    </template>
                    <span v-if="unitError" style="color: red;" class="error-message">{{ unitError }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="4" style="margin-bottom: 30px;">
                  <el-checkbox v-model="formData.multiUnit">多单位</el-checkbox>
                </el-col>
              </el-row>

            </el-col>

            <el-col :span="6">
              <el-form-item label="颜色">
                <el-input placeholder="请输入颜色" v-model="formData.color"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="基础重量">
                <el-input-number v-model="formData.weight" :min="0" placeholder="请输入基础重量(kg)"
                  controls-position="right" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="保质期">
                <el-input-number v-model="formData.expiryNum" :min="0" placeholder="请输入保质期(天)"
                  controls-position="right" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="类别:">
                <el-tree-select v-model="formData.categoryId"
                  :props="{ value: 'id', label: 'name', children: 'children' }" :data="organTreeData"
                  :render-after-expand="false" check-strictly clearable />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="序列号">
                <el-select v-model="formData.enableSerialNumber">
                  <el-option label="有" :value="1"></el-option>
                  <el-option label="无" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="批号">
                <el-select v-model="formData.enableBatchNumber">
                  <el-option label="有" :value="1"></el-option>
                  <el-option label="无" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="仓位货架">
                <el-input placeholder="请输入仓位货架" v-model="formData.position"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="多属性">
                <template v-if="formData.unit">
                  <el-select v-model="value1" multiple placeholder="请选择" @change="SelectionChange" style="width: 100%;">
                    <el-option v-for="item in options" :key="item.id" :label="item.attributeName" :value="item.id" />
                  </el-select>
                </template>
                <template v-else>
                  <el-input placeholder="需现录入单位才能激活" v-model="formData.position" readonly></el-input>
                </template>
              </el-form-item>
            </el-col>
             <div v-for="attribute in selectedAttributes" :key="attribute"> 
                <el-form-item >
                  <el-input v-model="formData[attribute]" :placeholder="'请输入 ' + attribute"></el-input>
                 </el-form-item>
                </div>
          </el-row>

          <el-row>
            <el-button type="primary" @click="addRow" class="ant-btn ant-btn-primary">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
              <span>插入行</span>
            </el-button>
            <el-button type="primary" @click="removeSelectedRows" class="ant-btn ant-btn-danger"
              v-if="selectedRows.length > 0">
              <el-icon class="el-icon-left">
                <Minus />
              </el-icon>
              <span>移除行</span>
            </el-button>
            <el-button class="ant-btn ant-btn-primary">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
              <span>采购价-批量</span>
            </el-button>
            <el-button class="ant-btn ant-btn-primary">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
              <span>零售价-批量</span>
            </el-button>
            <el-button class="ant-btn ant-btn-primary">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
              <span>销售价-批量</span>
            </el-button>
            <el-button class="ant-btn ant-btn-primary">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
              <span>最低售价-批量</span>
            </el-button>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-table :data="tableData" @selection-change="handleSelectionChange"
                style="width: 100%; margin-top: 10px; border: 1px solid #e0e0e0; border-collapse: collapse;">
                <el-table-column type="selection" width="55" />
                <el-table-column label="条码" width="120">
                  <template #default="{ row }">
                    <el-input v-model="row.barcode"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单位" width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.unit" placeholder="请输入单位"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="采购价" width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.erpMaterialExtend.purchaseDecimal" placeholder="请输入采购价"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="零售价" width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.erpMaterialExtend.commodityDecimal" placeholder="请输入零售价"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="销售价" width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.erpMaterialExtend.wholesaleDecimal" placeholder="请输入销售价"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="最低售价" width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.erpMaterialExtend.lowDecimal" placeholder="请输入最低售价"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="商品初始库存" width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.erpMaterialExtend.initialInventory" placeholder="请输入商品初始库存"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>

            <el-col :span="24" style="padding: 0;">
              <el-form-item style="margin-top: 5px; width: 100%;">
                <el-input :autosize="{ minRows: 1, maxRows: 4 }" type="textarea" placeholder="请输入备注"
                  v-model="formData.remark" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="扩展信息">
          <div style="width: 25%;" margin-top="500px">
            <div>
              <el-form-item label="制造商">
                <el-input v-model="formData.mfrs"></el-input>
              </el-form-item>
            </div>
            <div></div>
            <el-form-item label="自定义1">
              <el-input v-model="formData.otherField1"></el-input>
            </el-form-item>

            <el-form-item label="自定义2">
              <el-input v-model="formData.otherField2"></el-input>
            </el-form-item>

            <el-form-item label="自定义3">
              <el-input v-model="formData.otherField3"></el-input>
            </el-form-item>
          </div>
        </el-tab-pane>

        <!-- <el-tab-pane label="库存数量">
          <el-form-item label="仓库">
            <el-input v-model="formData.warehouse" placeholder="请输入仓库"></el-input>
          </el-form-item>

          <el-form-item label="期初库存数量">
            <el-input-number v-model="formData.initialStock" :min="0" placeholder="请输入数量" />
          </el-form-item>

          <el-form-item label="最低安全库存数量">
            <el-input-number v-model="formData.lowSafeStock" :min="0" placeholder="请输入数量" />
          </el-form-item>

          <el-form-item label="最高安全库存数量">
            <el-input-number v-model="formData.highSafeStock" :min="0" placeholder="请输入数量" />
          </el-form-item>
        </el-tab-pane> -->

        <!-- <el-tab-pane label="图片信息">
          <el-form-item label="图片">
            <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" list-type="picture-card"
              :on-preview="handlePictureCardPreview" :on-change="handleChange">
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">最多上传4张，单张大小不超过1M</div>
            </el-upload>
          </el-form-item>
        </el-tab-pane> -->
      </el-tabs>

      <el-row style="margin-top: 200px; border-top: #e0e0e0 1px solid;">
        <el-col :span="24" :offset="0" style="margin-top: 10px;">
          <el-form-item style="float: right">
            <el-button @click="close">关 闭</el-button>
            <el-button type="primary" @click="onSubmit">确 定</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, defineEmits, onMounted, defineProps } from 'vue';
import reqeust from '@/api/request';
import router from '@/router';
import { Plus } from '@element-plus/icons-vue'; // 引入 Plus 图标
import { ElMessage } from 'element-plus';

// 接收传入的 props
const props = defineProps(['data']);
let emits = defineEmits(['close']);
let close = () => {
  emits('close');
};





// 在 script setup 中添加
const selectedAttributes = ref([]);
const selectedAttributeNames = ref([]); // 新增变量用于存储选中选项的名称






let currentBarcode = ref(''); // 用于存储当前的最大条码
// Table 数据
const tableData = ref([
  {
    barcode: "", // 使用当前条码并自增
    unit: '',
    erpMaterialExtend: {
      purchaseDecimal: '',
      commodityDecimal: '',
      wholesaleDecimal: '',
      lowDecimal: ''
    }
  }
]);

// 更新表格中每一行的单位值
const updateUnits = () => {
  tableData.value.forEach(row => {
    row.unit = formData.value.unit; // 将表单中的单位同步给每一行
  });
};

// 初始化时，将传入的当前条码设置到 tableData 的第一行
onMounted(() => {
  if (props.data && props.data.barcode) {
    currentBarcode.value = parseInt(props.data.barcode) + 1; // 获取传入的当前条码
    tableData.value[0].barcode = currentBarcode.value; // 将条码存入表格的第一行
  }
});

let formData = ref({
  name: '',
  standard: '',
  model: '',
  unit: '',
  unitId: '',
  color: '',
  weight: '',
  expiryNum: '',
  position: '',
  remark: '',
  enableSerialNumber: 0,
  enableBatchNumber: 0,
  categoryId: null,
  mfrs: '',
  otherField1: '',
  otherField2: '',
  otherField3: '',
});

const da = ref([]);
// 声明一个响应式变量，存储选择的数据
const selectedData = ref(null);
// 查询多单位
let findsuppliers = () => {
  reqeust({
    url: '/commodity/unit/list',
    method: 'get'
  }).then(resp => {
    da.value = resp.data
  })
}
findsuppliers();




const options = ref([]);

let AttributeService = () => {
  reqeust({
    url: '/commodity/material_attribute/list',
    method: 'get'
  }).then(resp => {
    console.log("请求成功", resp.data);
    options.value = resp.data;
  }).catch(error => {
    console.error("请求失败", error);
  });
};

AttributeService();



// 定义 handleUnitChange 函数
let handleUnitChange = (value) => {
  console.log('选中的单位ID:', value);

  reqeust.get('/commodity/unit/select/' + value)
    .then(response => {
      if (response.data) {
        console.log('返回的数据:', response.data);
        selectedData.value = response.data; // 将返回的数据存储在 selectedData 中
        console.log("选中的单位", selectedData.value);
        // 获取 basicUnit 的值
        const basicUnit = selectedData.value[0].basicUnit;
        console.log("基本单位", basicUnit);
        tableData.value.forEach(row => {
          row.unit = basicUnit; // 将单位值同步给每一行
        });
      }
    })
    .catch(error => {
      console.error('请求失败:', error);
    });
};


// 添加一行
const addRow = () => {
  const lastRowUnit = tableData.value.length > 0 ? tableData.value[tableData.value.length - 1].unit : '';
  tableData.value.push({
    barcode: currentBarcode.value + 1,
    unit: lastRowUnit,
    erpMaterialExtend: {
      initialInventory: '1',
      purchaseDecimal: '',
      commodityDecimal: '',
      wholesaleDecimal: '',
      lowDecimal: '',

    }
  });
  currentBarcode.value++;
};
// 声明响应式变量
let nameError = ref(''); // 存储名称的错误信息
let unitError = ref(''); // 存储单位的错误信息
// 提交表单的方法
const onSubmit = () => {

  nameError.value = '';
  unitError.value = '';
  // 验证必填项
  if (!formData.value.name) {
    nameError.value = '请输入名称！';
  }
  if (formData.value.multiUnit && !formData.value.unitId) {
    unitError.value = '请输入单位！';
  } else if (!formData.value.multiUnit && !formData.value.unit) {
    unitError.value = '请输入单位！';
  }

  // 如果有错误，不提交
  if (nameError.value || unitError.value) {
    return;
  }
  const requestData = {
    material: formData.value,
    materialExtends: tableData.value.map(row => ({
      barCode: row.barcode,
      commodityUnit: row.unit,
      initialInventory: row.erpMaterialExtend.initialInventory,
      purchaseDecimal: row.erpMaterialExtend.purchaseDecimal,
      commodityDecimal: row.erpMaterialExtend.commodityDecimal,
      wholesaleDecimal: row.erpMaterialExtend.wholesaleDecimal,
      lowDecimal: row.erpMaterialExtend.lowDecimal,
    }))
  };

  console.log("提交表单数据:", requestData);

  // 发送请求到后台接口
  reqeust.post('/commodity/material/add', requestData, {
    headers: {
      'Content-Type': 'application/json',
    },
  }).then(resp => {
    console.log("请求成功", resp);
    if (resp.code === 200) {
      ElMessage.success('添加成功');
      router.push("/commodity/material")
      emits('close');
    }
  }).catch(error => {
    console.error('出错了', error);
  });
};

// 加载类别数据
const organTreeData = ref([]);
const findOrgan = () => {
  reqeust.get('cam/findOrganTree').then(resp => {
    if (resp.code == 200) {
      organTreeData.value = resp.data;
    }
  })
}

const selectedRows = ref([]);

const handleSelectionChange = (selected) => {
  selectedRows.value = selected;
};

const removeSelectedRows = () => {
  const selectedBarcodes = selectedRows.value.map(row => row.barcode);
  tableData.value = tableData.value.filter(row => !selectedBarcodes.includes(row.barcode));
  selectedRows.value = []; // 清空选中的行
};

const SelectionChange = (newValue) => {
  if (newValue.length > 3) {

    // 强制保留最后三个选择的值
    value1.value = newValue.slice(0, 3);
  }
  selectedAttributes.value = newValue; // 更新选中项
   // 更新选中选项的名称
   selectedAttributeNames.value = options.value
    .filter(item => newValue.includes(item.id)) // 过滤出选中的项
    .map(item => item.attributeName); // 获取选中项的名称
};

const value1 = ref([]);


findOrgan();
</script>

<style scoped>
.el-tabs {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-table {
  width: 100%;
  /* 确保表格宽度占满 */
  border: 1px solid #e0e0e0;
  /* 最外层边框 */
}

.el-table th,
.el-table td {
  border: none;
  /* 去掉竖线 */
}

.el-table tr {
  border-bottom: 1px solid #e0e0e0;
  /* 添加横线 */
}
</style>
